package com.maodou.android.ui.page.home

import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.outlined.Menu
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Surface
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.zIndex
import com.maodou.android.ui.page.SearchKey
import com.maodou.core.navigation.Navigator3
import com.maodou.core.ui.components.ActionBar
import com.maodou.core.ui.components.ActionItem
import com.maodou.core.ui.components.TitleAlignment
import kotlinx.coroutines.launch
import kotlin.math.roundToInt

import androidx.compose.foundation.background
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.layout.widthIn
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.hilt.navigation.compose.hiltViewModel
import com.maodou.android.ui.page.DetailKey
import com.maodou.android.ui.page.EditAccountKey
import com.maodou.android.ui.page.ImportKey
import com.maodou.android.viewmodel.account.AccountViewModel
import com.maodou.android.viewmodel.main.MainViewModel
import com.maodou.core.navigation.NavigationAnimation
import com.maodou.core.ui.components.AppText
import com.maodou.core.ui.components.debouncedClickable
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.maodou.android.R
import com.maodou.android.data.model.AccountFilterParams
import com.maodou.android.ui.page.account.BottomWheelPicker
import com.maodou.core.navigation.DialogStyle
import com.maodou.core.navigation.GlobalUiBus
import com.maodou.core.navigation.LocalDialogHandle
import com.maodou.core.ui.components.EmptyCenterLayout
import com.maodou.core.ui.components.HSpacer

/**
 * @Author Xing
 * @CreateTime 2025年01月16日
 * @Description
 */
@Composable
fun HomeScreen(
    listState: LazyListState? = null,
    viewModel: MainViewModel = hiltViewModel(),
    accountModel: AccountViewModel = hiltViewModel(),
) {
    // 抽屉状态
    val drawerState = rememberDrawerState(DrawerValue.Closed)
    val scope = rememberCoroutineScope()
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    // 加载分类 tabs
    LaunchedEffect(Unit) { viewModel.loadAccountCategories() }
    val tabs = uiState.tabs
    val pagerState = rememberPagerState(initialPage = 0, pageCount = { tabs.size.coerceAtLeast(1) })

    ModalNavigationDrawer(
        drawerState = drawerState,
        drawerContent = {
            HomeDrawerUI(drawerState){
                viewModel.logout()
            }
        }
    ) {
        // 限制悬浮按钮拖动边界并获取容器尺寸
        BoxWithConstraints(modifier = Modifier.fillMaxSize()) {

            Column(modifier = Modifier.fillMaxSize()) {
                // 顶部栏
                ActionBar(
                    title = stringResource(R.string.app_name),
                    modifier = Modifier.fillMaxWidth(),
                    navigationIcon = Icons.Outlined.Menu,
                    onNavigationClick = {
                        scope.launch { drawerState.open() }
                    },
                    backgroundColor = Color.Transparent,
                    contentColor = MaterialTheme.colorScheme.onSurface,
                    titleAlignment = TitleAlignment.Center,
                    actions = listOf(
                        ActionItem(
                            icon = Icons.Filled.Search,
                            contentDescription = "搜索",
                            onClick = {  Navigator3.navigate(SearchKey) }
                        )
                    )
                )

                // 页面主体
                Box(modifier = Modifier.fillMaxSize()) {
                    BoxWithConstraints(modifier = Modifier.fillMaxSize()) {
                        val density = LocalDensity.current
                        val maxWidthPx = with(density) { maxWidth.toPx() }
                        val maxHeightPx = with(density) { maxHeight.toPx() }

                        val fabSize = 56.dp
                        val margin = 16.dp
                        val fabSizePx = with(density) { fabSize.toPx() }
                        val marginPx = with(density) { margin.toPx() }

                        var expanded by rememberSaveable { mutableStateOf(false) }

                        var offsetX by rememberSaveable { mutableFloatStateOf(0f) }
                        var offsetY by rememberSaveable { mutableFloatStateOf(0f) }

                        val topBarHeightPx by remember { mutableIntStateOf(0) }
                        var hasInit by rememberSaveable { mutableStateOf(false) }

                        // FAB 旋转动画
                        val rotation by animateFloatAsState(
                            targetValue = if (expanded) 45f else 0f,
                            animationSpec = tween(300),
                            label = "fab_rotation"
                        )

                        Column(modifier = Modifier.fillMaxSize()) {

                            Box(modifier = Modifier.fillMaxSize()) {
                                val availableHeightPx = maxHeightPx - topBarHeightPx.toFloat()

                                LaunchedEffect(maxWidthPx, availableHeightPx) {
                                    if (!hasInit && maxWidthPx > 0 && availableHeightPx > 0) {
                                        offsetX =
                                            (maxWidthPx - fabSizePx - (marginPx*2)).coerceAtLeast(0f)
                                        offsetY =
                                            (availableHeightPx - fabSizePx - (marginPx*6)).coerceAtLeast(
                                                0f
                                            )
                                        hasInit = true
                                    }
                                }

                                Column(modifier = Modifier.fillMaxSize()) {
                                    if(tabs.isNotEmpty()){
                                        if(tabs.size > 1) Row(
                                            modifier = Modifier.fillMaxWidth(),
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                            ScrollableTabRow(
                                                selectedTabIndex = pagerState.currentPage,
                                                edgePadding = 0.dp,
                                                divider = {},
                                                containerColor = Color.Transparent,
                                                modifier = Modifier.weight(1f),
                                                indicator = { tabPositions ->
                                                    val indicatorWidth = 26.dp
                                                    val indicatorHeight = 4.dp
                                                    val current = tabPositions[pagerState.currentPage]
                                                    val indicatorOffsetX = current.left + (current.width - indicatorWidth) / 2
                                                    Box(Modifier.fillMaxSize()) {
                                                        Box(
                                                            Modifier
                                                                .align(Alignment.BottomStart)
                                                                .offset(x = indicatorOffsetX)
                                                                .width(indicatorWidth)
                                                                .height(indicatorHeight)
                                                                .clip(RoundedCornerShape(50))
                                                                .background(MaterialTheme.colorScheme.primary)
                                                        )
                                                    }
                                                }
                                            ) {
                                                tabs.forEachIndexed { index, title ->
                                                    val selected = pagerState.currentPage == index
                                                    Box(
                                                        contentAlignment = Alignment.Center,
                                                        modifier = Modifier
                                                            .widthIn(min = 60.dp)
                                                            .height(40.dp).debouncedClickable {
                                                                scope.launch { pagerState.animateScrollToPage(index) }
                                                            }
                                                    ){
                                                        AppText(
                                                            text = title,
                                                            color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
                                                            style = TextStyle(
                                                                fontSize = if (selected) 16.sp else 14.sp,
                                                                fontWeight = if (selected) FontWeight.Bold else FontWeight.Medium,
                                                            ),
                                                            modifier = Modifier.padding(horizontal = 12.dp)
                                                        )
                                                    }

                                                }
                                            }
                                            Row(
                                                verticalAlignment = Alignment.CenterVertically,
                                                modifier = Modifier
                                                    .padding(horizontal = 12.dp)
                                                    .height(40.dp)
                                                    .debouncedClickable {
                                                        GlobalUiBus.showPopup(
                                                            style = DialogStyle.Bottom,
                                                            dismissOnClickOutside = true,
                                                            dismissOnBackPress = true,
                                                            content = {
                                                                val handle = LocalDialogHandle.current
                                                                AccountFilterBottomSheet(
                                                                    viewModel = accountModel,
                                                                    onDismiss = { handle?.close() },
                                                                    onConfirm = { platforms, statuses, tags ->
                                                                        // TODO: 处理筛选结果
                                                                        handle?.close()
                                                                        accountModel.setAccountFilter(AccountFilterParams(platforms, statuses, tags))
                                                                    }
                                                                )
                                                            }
                                                        )
                                                    }
                                            ) {
                                                Text(
                                                    text = "筛选",
                                                    fontSize = 12.sp,
                                                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                                                )
                                                Icon(
                                                    painter = painterResource(R.mipmap.ic_account_filtr),
                                                    contentDescription = null,
                                                    modifier = Modifier.size(11.dp)
                                                )
                                            }

                                        }
                                        HorizontalPager(
                                            state = pagerState,
                                            modifier = Modifier.fillMaxSize()
                                        ) { page ->
                                            val tabTitle = tabs.getOrNull(page) ?: ""
                                            TabPageUI(
                                                tabIndex = page,
                                                listState = if (page == pagerState.currentPage) listState else null,
                                                type = tabTitle,
                                                isActive = page == pagerState.currentPage
                                            )
                                        }
                                    } else {
                                        EmptyCenterLayout()
                                    }
                                }

                                // 展开菜单
                                androidx.compose.animation.AnimatedVisibility(
                                    visible = expanded,
                                    enter = fadeIn(animationSpec = tween(300)) +
                                            scaleIn(animationSpec = tween(300)) +
                                            slideInVertically(
                                                animationSpec = tween(300),
                                                initialOffsetY = { it / 2 }
                                            ),
                                    exit = fadeOut(animationSpec = tween(200)) +
                                            scaleOut(animationSpec = tween(200)) +
                                            slideOutVertically(
                                                animationSpec = tween(200),
                                                targetOffsetY = { it / 2 }
                                            )
                                ) {
                                    // 计算菜单位置
                                    val menuWidth = with(density) { 80.dp.toPx() } // 估算菜单宽度
                                    val menuHeight =
                                        with(density) { 100.dp.toPx() }

                                    val menuOffsetX = (offsetX + fabSizePx / 2 - menuWidth / 2)
                                        .coerceIn(marginPx, maxWidthPx - menuWidth - marginPx)
                                    val menuOffsetY =
                                        (offsetY - menuHeight + 50f - with(density) { 8.dp.toPx() })
                                            .coerceAtLeast(marginPx)

                                    Column(
                                        modifier = Modifier
                                            .wrapContentSize()
                                            .zIndex(1f)
                                            .offset {
                                                IntOffset(
                                                    menuOffsetX.roundToInt(),
                                                    menuOffsetY.roundToInt()
                                                )
                                            },
                                        horizontalAlignment = Alignment.CenterHorizontally,
                                        verticalArrangement = Arrangement.spacedBy(8.dp)
                                    ) {
                                        MiniActionChip(
                                            text = "批量导入",
                                            onClick = {
                                                expanded = false
                                                Navigator3.navigate(ImportKey)
                                            }
                                        )
                                        MiniActionChip(
                                            text = "添加账号",
                                            onClick = {
                                                expanded = false
                                                Navigator3.navigate(EditAccountKey())
                                            }
                                        )
                                    }
                                }

                                // 悬浮按钮
                                FloatingActionButton(
                                    onClick = { expanded = !expanded },
                                    containerColor = MaterialTheme.colorScheme.primary,
                                    modifier = Modifier
                                        .offset {
                                            IntOffset(
                                                offsetX.roundToInt(),
                                                offsetY.roundToInt()
                                            )
                                        }
                                        .size(fabSize)
                                        .pointerInput(Unit) {
                                            detectDragGestures { _, dragAmount ->
                                                val availableH = availableHeightPx
                                                val newX = (offsetX + dragAmount.x)
                                                    .coerceIn(0f, maxWidthPx - fabSizePx)
                                                val newY = (offsetY + dragAmount.y)
                                                    .coerceIn(
                                                        0f,
                                                        (availableH - fabSizePx).coerceAtLeast(0f)
                                                    )
                                                offsetX = newX
                                                offsetY = newY
                                            }
                                        }
                                ) {
                                    Icon(
                                        imageVector = Icons.Filled.Add,
                                        contentDescription = "添加",
                                        tint = Color.White,
                                        modifier = Modifier.rotate(rotation)
                                    )
                                }
                            }
                        }
                    }
                }
            }

        }
    }
}


@Composable
private fun MiniActionChip(text: String, onClick: () -> Unit) {
    Surface(
        color = Color(0xFFE6E6E6),
        shape = MaterialTheme.shapes.medium,
        shadowElevation = 2.dp,
        modifier = Modifier
            .wrapContentSize()
            .clickable(onClick = onClick)
    ) {
        Text(
            text = text,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
            style = MaterialTheme.typography.bodyMedium,
            modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp)
        )
    }
}

@Preview(backgroundColor = 0xffffffff)
@Composable
fun HomeScreenPreview(){
    HomeScreen()
}